package org.ThreadDemo.sync;

class Share2 {
    private int number = 0;

    public synchronized void incr() throws InterruptedException{



//        if(number !=0 ) {
//            try {
//                this.wait();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }
//
//        if (number == 0) {
//            number ++ ;
//            System.out.println(Thread.currentThread().getName()+"::"+number);
//        }
//        this.notifyAll();


        while(number != 0) {
            this.wait();
        }
        number++ ;
        System.out.println(Thread.currentThread().getName()+"::"+number);
        this.notifyAll();

    }

    public synchronized void decr() throws InterruptedException{

        while(number !=1 ){
            this.wait();
        }

        number--;
        System.out.println(Thread.currentThread().getName()+"::"+number);
        this.notifyAll();

    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {
        Share2 share = new Share2();

        new Thread( ()-> {
            for(int i = 1;i<=100;i++){
                try{
                    share.incr();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread( ()-> {
            for(int i = 1;i<=100;i++){
                try{
                    share.decr();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();


        new Thread( ()-> {
            for(int i = 1;i<=100;i++){
                try{
                    share.incr();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();


        new Thread( ()-> {
            for(int i = 1;i<=100;i++){
                try{
                    share.decr();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();



    }

}
